<?php

/**
 * RabbitCMS
 */
class Core_Models_Translation extends Rabbit_Db_Table_Abstract implements Core_Models_Interfaces_Translation {

    protected $_name = 'core_translation';

    /**
     *
     * @param array $params
     * @return int Id of new translattion
     */
    public function convert($params) {
        return null;
    }

    /**
     * Add new translation
     * @param Core_Models_Entities_Translation $translation
     * @return int
     */
    public function add($translation) {
        try {
            $tr = $this->createRow(array(
                'item_id' => $translation->item_id,
                'item_class' => $translation->item_class,
                'source_item_id' => $translation->source_item_id,
                'language' => $translation->language,
                'source_language' => $translation->source_language,
                    ));
            $tr->save();
            return $tr->id;
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    public function update($translation) {
        return $this->getAdapter()->update($this->_name, array(
                    'source_item_id' => $translation->source_item_id,
                    'language' => $translation->language,
                    'source_language' => $translation->source_language,
                        ), array(
                    'item_id = ?' => $translation->item_id,
                    'item_class = ?' => $translation->item_class,
                ));
        
    }

    public function delete($id, $class) {
        $this->getAdapter()->update($this->_name, array(
            'source_item_id' => new Zend_Db_Expr('item_id'),
            'source_language' => null,
                ), array(
            'source_item_id = ?' => $id,
            'item_class = ?' => $class,
        ));

        return $this->getAdapter()->delete($this->_name, array(
                    'item_id = ?' => $id,
                    'item_class = ?' => $class,
                ));
    }

    public function getItems($id, $class, $lang = null) {

        $select = $this->getAdapter()->select()
                ->from(array('tr1' => $this->_prefix . 'core_translation'))
                ->joinInner(array('tr2' => $this->_prefix . 'core_translation'), '(tr1.item_id = ? AND tr1.source_item_id = tr2.item_id)
									OR (tr2.item_id = ? AND tr1.item_id = tr2.source_item_id)
									OR (tr1.source_item_id = ? AND tr1.source_item_id = tr2.source_item_id)', array())
                ->where('tr1.item_class = ?', $class);
        if ($lang != null) {
            $select->where('tr1.language = ?', $lang);
        }
        $rs = $select->where('tr2.item_class = ?', $class)
                ->group('tr1.id')
                ->bind(array($id, $id, $id))
                ->query()
                ->fetchAll();
        return $rs;
    }

}

